package com.cuit.config;

import com.cuit.pojo.Admin;
import com.cuit.service.AdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * @author chishuiLi     Email:1192537447@qq.com
 * @Description 自定义的realm  extends AuthorizingRealm
 */
public class UserRealm  extends AuthorizingRealm {

    @Resource
    private AdminService adminService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

//        info.addStringPermission("user:add");

        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        Admin currentUser = (Admin) subject.getPrincipal();
//        User currentUser = (User)subject.getPrincipal();  //拿到user对象了

        //设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证");

        //用户名 密码  数据库中取
//        String name = "root";
//        String password = "123456";

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String adminName = token.getUsername();
//        if(!token.getUsername().equals(name)){
//            return null;  //抛出异常 UnknownAccountException 用户名不存在
//        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("adminname",adminName);
        List<Admin> adminList = adminService.listByMap(map);
        if(adminList.size() == 0){
            return null;  //抛出异常 UnknownAccountException 用户名不存在
        }

        Admin admin = adminList.get(0);
        //登录成功
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",admin);

        //密码认证 ，shiro做
        return new SimpleAuthenticationInfo(admin,admin.getAdminpw(),"");
//        return new SimpleAuthenticationInfo(user,password,"");
    }
}
